package com.carnation._synchronized_utility;

import java.util.Random;
import java.util.concurrent.*;

/**
 * <p>
 * Semaphore
 * </p>
 *
 * @author: Sunny
 * @date: 2021/2/4
 * @version: v1.0.0
 */
public class SemphoreTest {

    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(2, true);
        ExecutorService threadPool = new ThreadPoolExecutor(3, 3, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<>(10));
        final Random random = new Random();
        for (int i = 0; i < 10; i++) {
            threadPool.execute(() -> {
                long id = Thread.currentThread().getId();
                try {
                    semaphore.acquire();
                    System.out.println(id + "获取到锁");
                    int t = random.nextInt(5);
                    TimeUnit.SECONDS.sleep(t + 1);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    System.out.println(id + "释放锁");
                    semaphore.release();
                }
            });
        }
    }
}
